package com.itheima.stock.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.stock.pojo.entity.SysUser;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.service.SysUserService;
import com.itheima.stock.vo.resp.ResponseCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/sysUser")
@RestController
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/pageList")
    public R<IPage<SysUser>> pageList(){
        IPage<SysUser> page = new Page<>(1, 10);
        sysUserService.page(page);

        return R.ok(page);
    }


    @PostMapping("/login")
    public R<LoginRespVo> login(@RequestBody LoginReqVo vo){
        if(vo == null){
            return R.error(ResponseCode.DATA_ERROR);
        }
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(!StringUtils.isBlank(vo.getUsername()),SysUser::getUsername,vo.getUsername());
        // 没有查询条件直接登录失败
        if(queryWrapper.getSqlSelect() == null){
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }
        SysUser user = sysUserService.getOne(queryWrapper);
        if(user == null){
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }
        boolean isLogin = passwordEncoder.matches(vo.getPassword(), user.getPassword());
        if(!isLogin){
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }
        LoginRespVo loginRespVo = new LoginRespVo();
        BeanUtils.copyProperties(user,loginRespVo);
        return R.ok(loginRespVo);
    }
}
